package com.easy.cloud.web.oauth.configuration;

import cn.hutool.core.collection.CollUtil;
import com.easy.cloud.web.oauth.social.SecurityAuthenticationFailureHandler;
import com.easy.cloud.web.oauth.social.SecurityAuthenticationSuccessHandler;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * @author GR
 * @date 2021-3-26 16:48
 */
@Configuration
public class OauthAutoConfiguration implements InitializingBean {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    /**
     * https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-updated
     * Encoded password does not look like BCrypt
     *
     * @return PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }


    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new SecurityAuthenticationFailureHandler();
    }

    @Bean
    public AuthenticationSuccessHandler mobileLoginSuccessHandler() {
        return new SecurityAuthenticationSuccessHandler();
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        tokenEndpoint.setAllowedRequestMethods(CollUtil.newHashSet(HttpMethod.GET, HttpMethod.POST));
    }
}
